﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Telerik.Web.Mvc;

namespace Presentation.Web.Admin.Controllers
{
    [HandleError]
    public class TourController : Infrastructure.Crosscutting.NetFramework.Controllers.BaseController
    {
        Application.Admin.Tour.ITourClassService claService;

        Application.Admin.Tour.ITourImportLogService imLogService;

        Application.Admin.Tour.ITourPicService tourPicService;

        Application.Admin.Tour.ITourService tourService;

        Application.Admin.Tour.ITourSightService tourSightService;

        Application.Admin.Pic.IPicInfoService picService;

        Application.Admin.Sight.ISightPointService sightService;

        public TourController(Infrastructure.Crosscutting.NetFramework.IWorkContext work,
            Application.Admin.Tour.ITourClassService cla,
            Application.Admin.Tour.ITourImportLogService imLog,
            Application.Admin.Tour.ITourPicService tourPic,
            Application.Admin.Tour.ITourService tour,
            Application.Admin.Tour.ITourSightService tourSight,
            Application.Admin.Pic.IPicInfoService pic,
            Application.Admin.Sight.ISightPointService sight)
            : base(work)
        {
            if (cla == null)
            {
                throw new ArgumentNullException("claService is null");
            }
            if (imLog == null)
            {
                throw new ArgumentNullException("imLogService is null");
            }
            if (tourPic == null)
            {
                throw new ArgumentNullException("tourPicService is null");
            }
            if (tour == null)
            {
                throw new ArgumentNullException("tourService is null");
            }
            if (tourSight == null)
            {
                throw new ArgumentNullException("tourSightService is null");
            }
            if (pic == null)
            {
                throw new ArgumentNullException("picService is null");
            }
            if (sight == null)
            {
                throw new ArgumentNullException("sightService is null");
            }
            claService = cla;
            imLogService = imLog;
            tourPicService = tourPic;
            tourService = tour;
            tourSightService = tourSight;
            picService = pic;
            sightService = sight;
        }

        #region tour

        public ViewResult Index()
        {
            var data = this.GetTourTrueState();
            return View(data.ToDto());
        }

        [GridAction]
        public JsonResult AjaxIndex(string searchKey)
        {
            var data = this.GetTourTrueState();
            if (!string.IsNullOrEmpty(searchKey))
            {
                data = data.Where(e => e.Name.Contains(searchKey));
            }
            var dto = data.ToDto();
            var model = new GridModel<Domain.Dto.TourDto>
            {
                Data = dto,
                Total = dto.Count()
            };
            return new JsonResult { Data = model, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }

        [HttpPost]
        public JsonResult Add(Domain.Dto.TourDto dto)
        {
            var res = false;
            var message = "";
            dto.AddTime = System.DateTime.Now;
            dto.AudTime = null;
            dto.BeginTime = System.DateTime.Now;
            dto.CustomDateTime = string.IsNullOrEmpty(dto.CustomDateTime) ? "" : dto.CustomDateTime.Trim();
            dto.DeleteTime = null;
            dto.EndTime = System.DateTime.Now;
            dto.IpAddress = Infrastructure.Crosscutting.Comm.Service.StringService.GetRealIP();
            dto.IsAud = true;
            dto.IsDelete = false;
            dto.IsTop = false;
            dto.IsVouch = false;
            dto.ModifyTime = System.DateTime.Now;
            dto.Name = string.IsNullOrEmpty(dto.Name) ? "" : dto.Name.Trim();
            dto.Remark = string.IsNullOrEmpty(dto.Remark) ? "" : dto.Remark.Trim();
            dto.SortNum = 0;
            dto.TopTime = null;
            dto.UserId = this.WorkContext.CurrentUser.Id;
            dto.UserName = this.WorkContext.CurrentUser.UserName;
            dto.VouchTime = null;
            var entity = dto.ToEntity();
            tourService.Add(entity, this.WorkContext.CurrentUser);
            if (entity.Id > 0)
            {
                res = true;
            }
            else
            {
                message = "添加失败了T_T";
            }
            return Json(new { success = res, message = message }, JsonRequestBehavior.AllowGet);
        }

        [GridAction]
        [HttpPost]
        public JsonResult Delete(int id)
        {
            var delete = tourService.Get(id);
            if (delete != null)
            {
                tourService.DeleteTrue(delete, this.WorkContext.CurrentUser);
            }
            var data = this.GetTourTrueState().ToDto();
            return Json(data, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public JsonResult MulDelete(FormCollection del)
        {
            var res = false;
            var message = "";
            var selectedList = del.GetValues("selectRow");
            if (selectedList != null && selectedList.Count() > 0)
            {
                res = tourService.DeleteTrue(selectedList.ToIntList(), this.WorkContext.CurrentUser);
                message = res == true ? "" : "删除失败了，T_T";
            }
            //返回空，是为了不再请求数据，因为他自己会重新binding的
            return Json(new { success = res, message = message }, JsonRequestBehavior.AllowGet);
        }

        [GridAction]
        [HttpPost]
        public JsonResult Edit(Domain.Dto.TourDto dto)
        {
            if (dto.Id > 0)
            {
                var entity = tourService.Get(dto.Id);
                if (entity != null && entity.Id > 0)
                {
                    entity.Name = string.IsNullOrEmpty(dto.Name) ? "" : dto.Name.Trim();
                    entity.Remark = string.IsNullOrEmpty(dto.Remark) ? "" : dto.Remark.Trim();
                    entity.CustomDateTime = string.IsNullOrEmpty(dto.CustomDateTime) ? "" : dto.CustomDateTime.Trim();
                    entity.ModifyTime = System.DateTime.Now;
                    tourService.Modify(entity, this.WorkContext.CurrentUser);
                }
            }
            var data = this.GetTourTrueState();
            var model = new GridModel<Domain.Dto.TourDto>
            {
                Data = data.ToDto(),
                Total = data.Count()
            };
            return new JsonResult { Data = model, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }

        [HttpGet]
        public JsonResult Search(string term)
        {
            if (!string.IsNullOrEmpty(term))
            {
                var data = this.GetTourTrueState().Where(e => e.Name.Contains(term.Trim()))
                            .OrderBy(e => e.Id).Take(10)
                            .Select(e => e.Name).Distinct();
                return Json(data.ToList(), JsonRequestBehavior.AllowGet);
            }
            else
            {
                var data = this.GetTourTrueState().OrderBy(e => e.Id).Take(10)
                            .Select(e => e.Name).Distinct();
                return Json(data.ToList(), JsonRequestBehavior.AllowGet);
            }
        }

        #endregion

        #region tour detail

        public ViewResult TourDetailIndex(int id)
        {
            var data = this.GetTourSightTrueState(id).ToList();
            var model = tourService.Get(id);
            ViewBag.tour = model;
            return View(data);
        }

        [GridAction]
        public JsonResult AjaxTourDetailIndex(int targetId)
        {
            var data = this.GetTourSightTrueState(targetId).ToList();
            var model = new GridModel<Application.Admin.Dto.TourDetailDto>
            {
                Data = data,
                Total = data.Count()
            };
            return new JsonResult { Data = model, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }

        [HttpPost]
        public JsonResult AddTourDetail(Application.Admin.Dto.TourDetailDto dto)
        {
            var res = false;
            var message = "";
            var sightName = string.IsNullOrEmpty(dto.SightName) ? "" : dto.SightName.Trim();
            var sight = sightService.GetList().Where(e => e.Name == sightName).FirstOrDefault();
            var tour = tourService.Get(dto.TourId);
            if (sight != null)
            {
                if (tour != null)
                {
                    //更新版本号
                    tour.ModifyTime = System.DateTime.Now;
                    tourService.Modify(tour, this.WorkContext.CurrentUser);
                    //end 更新版本号
                    var entity = dto.ToEntity();
                    entity.AddTime = System.DateTime.Now;
                    entity.IpAddress = Infrastructure.Crosscutting.Comm.Service.StringService.GetRealIP();
                    entity.NextTips = string.IsNullOrEmpty(dto.NextTips) ? "" : dto.NextTips.Trim();
                    entity.CustomDateTime = string.IsNullOrEmpty(dto.CustomDateTime) ? "" : dto.CustomDateTime.Trim();
                    entity.Remark = string.IsNullOrEmpty(dto.Remark) ? "" : dto.Remark.Trim();
                    entity.SightId = sight.Id;
                    var selected = tourSightService.GetList().Where(e => e.TourId == dto.TourId);
                    var max = 1;
                    if (selected.Any())
                    {
                        max = selected.Max(e => e.SortNum) + 1;
                    }
                    entity.SortNum = max;
                    entity.State = true;
                    entity.TourId = dto.TourId;
                    entity.Day = dto.Day;
                    entity.IsShowInMap = true;
                    tourSightService.Add(entity, this.WorkContext.CurrentUser);
                    if (entity.Id > 0)
                    {
                        res = true;
                    }
                    else
                    {
                        message = "添加失败了T_T";
                    }
                }
                else
                {
                    message = "没有找到你要添加的线路Id";
                }
            }
            else
            {
                message = "没有找到，你想要添加的景点";
            }
            return Json(new { success = res, message = message }, JsonRequestBehavior.AllowGet);
        }

        [GridAction]
        [HttpPost]
        public JsonResult DeleteTourDetail(int id, int targetId)
        {
            var delete = tourSightService.Get(id);
            if (delete != null)
            {
                if (tourSightService.DeleteTrue(delete, this.WorkContext.CurrentUser))
                {
                    var tour = tourService.Get(targetId);
                    if (tour != null)
                    {
                        tour.ModifyTime = System.DateTime.Now;
                        tourService.Modify(tour, this.WorkContext.CurrentUser);
                    }
                }
            }
            var data = this.GetTourSightTrueState(targetId).ToList();
            return Json(data, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public JsonResult MulDeleteTourDetail(FormCollection del)
        {
            var res = false;
            var message = "";
            var selectedList = del.GetValues("selectRow");
            if (selectedList != null && selectedList.Count() > 0)
            {
                res = tourSightService.DeleteTrue(selectedList.ToIntList(), this.WorkContext.CurrentUser);
                //更新版本号    
                if (res)
                {
                    var targetIdStr = del.Get("targetId");
                    var targetId = 0;
                    int.TryParse(targetIdStr, out targetId);
                    if (targetId > 0)
                    {
                        var tour = tourService.Get(targetId);
                        if (tour != null)
                        {
                            tour.ModifyTime = System.DateTime.Now;
                            tourService.Modify(tour, this.WorkContext.CurrentUser);
                        }
                    }
                }
                message = res == true ? "" : "删除失败了，T_T";
            }
            //返回空，是为了不再请求数据，因为他自己会重新binding的
            return Json(new { success = res, message = message }, JsonRequestBehavior.AllowGet);
        }

        [GridAction]
        [HttpPost]
        public JsonResult EditTourDetail(Application.Admin.Dto.TourDetailDto dto, int targetId)
        {
            var tourSight = tourSightService.Get(dto.Id);
            if (tourSight != null)
            {
                tourSight.CustomDateTime = string.IsNullOrEmpty(dto.CustomDateTime) ? "" : dto.CustomDateTime.Trim();
                tourSight.NextTips = string.IsNullOrEmpty(dto.NextTips) ? "" : dto.NextTips.Trim();
                tourSight.Remark = string.IsNullOrEmpty(dto.Remark) ? "" : dto.Remark.Trim();
                tourSight.Day = dto.Day;
                tourSight.IsShowInMap = dto.IsShowInMap;
                tourSightService.Modify(tourSight, this.WorkContext.CurrentUser);
                var tour = tourService.Get(targetId);
                if (tour != null)
                {
                    tour.ModifyTime = System.DateTime.Now;
                    tourService.Modify(tour, this.WorkContext.CurrentUser);
                }
            }
            var data = this.GetTourSightTrueState(targetId).ToList();
            return Json(data, JsonRequestBehavior.AllowGet);
        }


        [HttpPost]
        public JsonResult TourSightDown(int id, int targetId)
        {
            var res = false;
            var message = "";
            var temp = tourSightService.GetList().Where(e => e.Id == id).FirstOrDefault();
            var max = tourSightService.GetList().Where(e => e.TourId == targetId)
                .Select(e => e.SortNum).Max();
            if (temp != null)
            {
                if (temp.SortNum == max)
                {
                    message = "已经不能再下移了";
                }
                else
                {
                    try
                    {
                        var tourSight = tourSightService.GetList().Where(e => e.TourId == targetId).ToList();
                        var sortNum = temp.SortNum;
                        foreach (var item in tourSight)
                        {
                            if (item.Id == temp.Id)
                            {
                                item.SortNum += 1;
                                tourSightService.Modify(item, this.WorkContext.CurrentUser);
                                continue;
                            }
                            if (item.SortNum == sortNum + 1)
                            {
                                item.SortNum -= 1;
                                tourSightService.Modify(item, this.WorkContext.CurrentUser);
                            }
                        }
                        res = true;

                        //更新版本号
                        var tour = tourService.Get(targetId);
                        if (tour != null)
                        {
                            tour.ModifyTime = System.DateTime.Now;
                            tourService.Modify(tour, this.WorkContext.CurrentUser);
                        }
                    }
                    catch (Exception ex)
                    {
                        message = ex.Message;
                    }
                }
            }
            else
            {
                message = "没有找到你要修改的对象";
            }
            return Json(new { success = res, message = message }, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public JsonResult TourSightUp(int id, int targetId)
        {
            var res = false;
            var message = "";
            var temp = tourSightService.GetList().Where(e => e.Id == id).FirstOrDefault();
            if (temp != null)
            {
                if (temp.SortNum <= 1)
                {
                    message = "已经不能再上移了";
                }
                else
                {
                    try
                    {
                        var tourSight = tourSightService.GetList().Where(e => e.TourId == targetId).ToList();
                        var sortNum = temp.SortNum;
                        foreach (var item in tourSight)
                        {
                            if (item.Id == temp.Id)
                            {
                                item.SortNum -= 1;
                                tourSightService.Modify(item, this.WorkContext.CurrentUser);
                                continue;
                            }
                            if (item.SortNum == sortNum - 1)
                            {
                                item.SortNum += 1;
                                tourSightService.Modify(item, this.WorkContext.CurrentUser);
                            }
                        }
                        res = true;
                        var tour = tourService.Get(targetId);
                        if (tour != null)
                        {
                            tour.ModifyTime = System.DateTime.Now;
                            tourService.Modify(tour, this.WorkContext.CurrentUser);
                        }
                    }
                    catch (Exception ex)
                    {
                        message = ex.Message;
                    }
                }
            }
            else
            {
                message = "没有找到你要修改的对象";
            }
            return Json(new { success = res, message = message }, JsonRequestBehavior.AllowGet);
        }

        #endregion

        #region tour class

        #endregion

        #region tour pic

        public JsonResult TourPicView(int id)
        {
            var res = false;
            var path = "";
            var message = "";
            var width = 0;
            var height = 0;
            var picId = tourPicService.GetList().Where(e => e.TourId == id)
                .OrderByDescending(e => e.Id)
                .ThenByDescending(e => e.AddTime)
                .Select(e => e.PicInfoId)
                .FirstOrDefault();
            var pic = picService.Get(picId);
            if (pic != null)
            {
                path = pic.WebFullPath;
                var phyPath = Server.MapPath("~" + path);
                var exist = System.IO.File.Exists(phyPath);
                if (exist)
                {
                    System.Drawing.Image image = System.Drawing.Image.FromFile(phyPath);
                    if (image != null)
                    {
                        width = image.Width;
                        height = image.Height;
                        image.Dispose();
                    }
                    res = true;
                }
                else
                {
                    message = "物理文件已经被删除了";
                }
            }
            else
            {
                message = "没有找到，你要浏览的图片地址T_T！，快去添加一张吧！";
            }
            return Json(new { success = res, width = width, height = height, path = path, message = message }, JsonRequestBehavior.AllowGet);
        }

        #endregion

        #region util

        protected IQueryable<Application.Admin.Dto.TourDetailDto> GetTourSightTrueState(int id)
        {
            var data = (from tourSight in tourSightService.GetList()
                        join sight in sightService.GetList() on tourSight.SightId equals sight.Id
                        where tourSight.TourId == id && tourSight.State == true
                        select new Application.Admin.Dto.TourDetailDto
                        {
                            AddTime = tourSight.AddTime,
                            Id = tourSight.Id,
                            IpAddress = tourSight.IpAddress,
                            NextTips = tourSight.NextTips,
                            SightId = tourSight.SightId,
                            SightName = sight.Name,
                            SortNum = tourSight.SortNum,
                            State = tourSight.State,
                            TourId = tourSight.TourId,
                            CustomDateTime = tourSight.CustomDateTime,
                            Remark = tourSight.Remark,
                            Day = tourSight.Day,
                            IsShowInMap = tourSight.IsShowInMap
                        }).OrderBy(e => e.SortNum);
            return data;
        }

        protected IQueryable<Domain.Entity.Tour> GetTourTrueState()
        {
            var data = tourService.GetList().Where(e => e.State == true)
                .OrderByDescending(e => e.Id).ThenByDescending(e => e.AddTime);
            return data;
        }

        #endregion
    }
}
